#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

const ull mod = 998244353;
const int N = 2e5 + 5;
const ull BASE = 911382629;
const ull MOD_HASH = 1e18 + 3;

int cnt[N];   
int len[N];
ull pos[N];   
vector<int> adj[N]; 
int m;

int getk(int u,int k) {
    if (adj[u].empty()) {
        return len[u];
    }
    
    for (int v : adj[u]) {
        if (k <= cnt[v]) {
            return getk(v,k);
        }
        k -= cnt[v];
    }
    return -1; 
}

void dfs1(int u, int cur_len){
    len[u] = cur_len;
    if (adj[u].empty()) { 
        cnt[u] = 1;
        pos[u] = len[u] * BASE + 1;
        return;
    }
    
    cnt[u] = 0;
    for (int v : adj[u]) {
        dfs1(v, cur_len + 1);
        cnt[u] += cnt[v];
    }
    
    sort(adj[u].begin(), adj[u].end(), [&](int x, int y) {
        int mn = min(cnt[x], cnt[y]);
        for (int k = 1; k <= mn; ++k) {
            int lx = getk(x,k);
            int ly = getk(y,k);
            if (lx != ly) return lx < ly;
        }
        return cnt[x] < cnt[y] || (cnt[x] == cnt[y] && x < y);
    });
    
    pos[u] = cnt[u]; 
    for (int v : adj[u]) {
        pos[u] = (pos[u] * BASE + pos[v]) % MOD_HASH;
    }
}

bool cmp(int x, int y) {
    if (pos[x] != pos[y]) return pos[x] < pos[y];
    
    int mn = min(cnt[x], cnt[y]);
    for (int k = 1; k <= mn; ++k) {
        int lx = getk(x, k);
        int ly = getk(y, k);
        if (lx != ly) return lx < ly;
    }
    return cnt[x] < cnt[y] || (cnt[x] == cnt[y] && x < y);
}

void dfs2(int u, ull cur_hash, vector<ull>& hashes) {
    if (adj[u].empty()) {
        hashes.push_back(cur_hash);
        return;
    }
    for (int i = 0; i < adj[u].size(); ++i) {
        int v = adj[u][i];
        ull c = i + 1;
        dfs2(v, cur_hash * mod + c, hashes);
    }
}

void clear() {
    for (int i = 1; i <= m; ++i) {
        cnt[i] = 0;
        len[i] = 0;
        pos[i] = 0;
        adj[i].clear();
    }
}

void solve() {
    cin >> m;
    for (int i = 2; i <= m; ++i) {
        int f;
        cin >> f;
        adj[f].push_back(i);
    }
    
    dfs1(1, 1); 

    for (int i = 1; i <= m; ++i) {
        sort(adj[i].begin(), adj[i].end(), cmp);
    }
    
    vector<ull> hashes;
    dfs2(1, 0, hashes);
    
    cout << hashes.size() << "\n";
    for (ull h : hashes) {
        cout << h << "\n";
    }
    
    clear();
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    
    int t;
    cin >> t;
    while (t--) {
        solve();
    }
    
    return 0;
}
